package com.itcast.admin.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcast.admin.domain.Setmeal;
import com.itcast.admin.domain.SetmealCategory;
import com.itcast.admin.domain.request.CreateSetmealReqDTO;
import com.itcast.admin.domain.request.SetmealPageReqDTO;
import com.itcast.admin.domain.response.GetSetmealResDTO;
import com.itcast.admin.domain.response.ItemAndGroupResDTO;
import com.itcast.admin.domain.response.SetmealPagerResDTO;
import com.itcast.admin.mapper.CheckupGroupMapper;
import com.itcast.admin.mapper.CheckupItemMapper;
import com.itcast.admin.mapper.SetmealMapper;
import com.itcast.admin.service.ISetmealCategoryService;
import com.itcast.admin.service.ISetmealService;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 套餐表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-11-05
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements ISetmealService {

    @Autowired
    private CheckupItemMapper checkupItemMapper;

    @Autowired
    private ISetmealCategoryService setmealCategoryService;

    @Autowired
    private CheckupGroupMapper checkupGroupMapper;
    /**
     * 分页查询套餐列表
     *
     * @param setmealPageReqDTO
     * @return
     */
    @Override
    public PageResult<SetmealPagerResDTO> pageQuery(SetmealPageReqDTO setmealPageReqDTO) {
        return PageHelperUtils.selectPage(setmealPageReqDTO, () -> baseMapper.pageQuery(setmealPageReqDTO));
    }



    /**
     * 新增套餐
     *
     * @param createSetmealReqDTO
     */
    @Override
    @Transactional
    public void createSetmeal(CreateSetmealReqDTO createSetmealReqDTO) {
        Setmeal setmeal = BeanUtils.copyBean(createSetmealReqDTO, Setmeal.class);
        List<Integer> itemIds = createSetmealReqDTO.getSetmealItemList().stream().map(itemAndGroup -> itemAndGroup.getItemId()).collect(Collectors.toList());
        //根据itemids查询体检项的价格总和
        BigDecimal totalPrice = checkupItemMapper.getTotalPrice(itemIds);
        setmeal.setSetmealCost(totalPrice);
        save(setmeal);
        Setmeal setmealDB = lambdaQuery().eq(Setmeal::getSetmealName, setmeal.getSetmealName()).one();
        Integer setmealId = setmealDB.getId();
        //向中间表存储数据
        createSetmealReqDTO.getSetmealItemList().forEach(itemAndGroup -> {
            baseMapper.insertItemAtSetmeal(setmealId, itemAndGroup.getItemId(),itemAndGroup.getGroupId());
        });
    }

    /**
     * @param id
     * @return
     */
    @Override
    public GetSetmealResDTO getSetmealById(Integer id) {
        return baseMapper.getSetmealById(id);
    }

    /**
     * 根据id修改套餐
     *
     * @param createSetmealReqDTO
     */
    @Override
    @Transactional
    public void updateSetmealById(Integer id,CreateSetmealReqDTO createSetmealReqDTO) {
        Setmeal setmeal = BeanUtils.copyBean(createSetmealReqDTO, Setmeal.class);
        Setmeal setmealDB = lambdaQuery().eq(Setmeal::getId, id).one();
        if (ObjectUtils.isEmpty(setmealDB)){
            throw new BadRequestException("套餐不存在");
        }
        //判断套餐名称是否重复
        Setmeal checkmeal = lambdaQuery().eq(Setmeal::getSetmealName, setmeal.getSetmealName())
                .ne(Setmeal::getId, setmeal.getId()).one();
        if (checkmeal != null){
            throw new BadRequestException("套餐名称已存在");
        }
        //取到体检项id集合
        List<Integer> itemIds = createSetmealReqDTO.getSetmealItemList().stream().map(itemAndGroup -> itemAndGroup.getItemId()).collect(Collectors.toList());
        //根据itemids查询体检项的价格总和
        BigDecimal totalPrice = checkupItemMapper.getTotalPrice(itemIds);
        setmeal.setSetmealCost(totalPrice);
        //更新套餐
        boolean update = lambdaUpdate().eq(Setmeal::getId, id).update(setmeal);
        if (!update){
            throw new BadRequestException("修改套餐失败");
        }
        //修改中间表的数据
        //先根据id删除,再添加
        baseMapper.deleteItemAtSetmeal(id);
        createSetmealReqDTO.getSetmealItemList().forEach(itemAndGroup -> {
            baseMapper.insertItemAtSetmeal(id, itemAndGroup.getItemId(),itemAndGroup.getGroupId());
        });
    }

    /**
     * 根据id禁用套餐
     *
     * @param id
     */
    @Override
    public void disableSetmealById(Integer id) {
        Setmeal setmeal = lambdaQuery().eq(Setmeal::getId, id).one();
        if (setmeal.getSetmealStatus() == 2) {
            throw new BadRequestException("套餐已禁用");
        }
        boolean update = lambdaUpdate().set(Setmeal::getSetmealStatus, 2).eq(Setmeal::getId, id).update();
        if (!update) {
            throw new BadRequestException("禁用套餐失败");
        }
    }

    /**
     * 根据id启用套餐
     *
     * @param id
     */
    @Override
    public void enableSetmealById(Integer id) {
        Setmeal setmeal = lambdaQuery().eq(Setmeal::getId, id).one();
        if (ObjectUtils.isEmpty(setmeal)){
            throw new BadRequestException("套餐不存在");
        }
        //查询所属的套餐类型状态是否启用
        SetmealCategory setmealCategory = setmealCategoryService.lambdaQuery().eq(SetmealCategory::getId, setmeal.getSetmealCategoryId()).one();
        if (setmealCategory.getSetmealCategoryStatus() == 2){
            throw new BadRequestException("套餐类型已禁用，请先启用套餐类型");
        }
        //启用套餐
        boolean update = lambdaUpdate().set(Setmeal::getSetmealStatus, 1).eq(Setmeal::getId, id).update();
        if (!update){
            throw new BadRequestException("启用套餐失败");
        }
    }

    /**
     * 根据id删除套餐
     *
     * @param id
     */
    @Override
    public void deleteSetmealById(Integer id) {
        Setmeal setmeal = lambdaQuery().eq(Setmeal::getId, id).one();
        if (ObjectUtils.isEmpty(setmeal)){
            throw new BadRequestException("套餐不存在");
        }
        if (!(setmeal.getSetmealStatus()==0)){
            throw new BadRequestException("该套餐状态有误,不能删除");
        }
        boolean removeById = removeById(id);
        if (!removeById){
            throw new BadRequestException("删除套餐失败");
        }
    }

    /**
     * 根据id查询检查项目录
     *
     * @param id
     */
    @Override
    public List<ItemAndGroupResDTO> queryCheckCategory(Integer id) {
        List<ItemAndGroupResDTO> itemAndGroupResDTOs = baseMapper.queryCheckCategory(id);

        itemAndGroupResDTOs.forEach(itemAndGroupResDTO -> {
            Integer groupId = itemAndGroupResDTO.getCheckGroupId();
            List<Integer> itemIds = checkupGroupMapper.getItemIdsBySetmealIdAndGroupId(id, groupId);
            //根据itemids查询总价
            BigDecimal totalPrice = checkupItemMapper.getTotalPrice(itemIds);
            itemAndGroupResDTO.setTotalPrice(totalPrice);
        });

        return itemAndGroupResDTOs;
    }
}
